# Create your views here.
import math
import os
# print(os.getcwd())
import joblib
import numpy as np
import pandas as pd
from django.contrib.auth import authenticate, login, logout
from django.db.models import Q
from django.forms import model_to_dict
from django.http import JsonResponse
# Create your views here.
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
# from time import *
from . import HuskyRecommender
from .models import Movie, Favorites, RecommendList, AdRecommendList, TagRecommendList, SummaryRecommendList, BigCover
from .models import UserInfo
# from .recommend_service import init_weight
from .utils import get_token, is_login
from . import recommend_service


# op_model = 0


@csrf_exempt
def verify_login(request):
    username = request.POST.get('username')
    # print(username)
    password = request.POST.get('password')
    # print(password)
    user = authenticate(username=username, password=password)
    if user is not None:
        login(request, user)
        token = get_token(username, 3600)
        UserInfo.objects.update_or_create(username=username, defaults={"token": 'is_login'})
        res = {
            'msg': '',
            'data': {
                'username': username,
                'token': token
            }
        }
        if len(RecommendList.objects.filter(user_id=user.id)) == 0:
            recommend_service.update_recommend(request)
        return JsonResponse(res)
        # return JsonResponse({'status': 1})
    else:
        res = {
            'msg': '用户名或密码错误'
        }
        return JsonResponse(res)


@csrf_exempt
def verify_logout(request):
    logout(request)
    UserInfo.objects.filter(username=request.POST.get('username')).update(token='is_logout')
    # user = UserInfo.objects.filter(username=request.POST.get('username'))
    # if len(user) == 0:
    #     return JsonResponse({'msg': '该账户未登录'})
    # user = user[0]
    # user.token = ''
    return JsonResponse({'msg': '该账户已注销'})


# 注册
@csrf_exempt
def register(request):
    if request.method == "POST":
        username = request.POST['username']
        # print(username)
        password = request.POST['password']
        email = request.POST["email"]
        user_registered = UserInfo.objects.filter(username=username)
        if len(user_registered) == 0:
            # print(user_registered)
            user = UserInfo.objects.create_user(username=username, password=password, email=email)
            res = {
                'msg': '',
                'data': {
                    'username': username,
                }
            }
            recommend_service.update_recommend(request)
            return JsonResponse(res)
        else:
            res = {
                'msg': '用户名已经存在',
            }
            return JsonResponse(res)


@csrf_exempt
def welcome_you(request):
    username = request.POST.get('username')
    status = UserInfo.objects.filter(username=username)
    if len(status) == 0:
        return JsonResponse({'msg': '该账户不存在'})
    status = status[0]
    if status.token == 'is_logout':
        return JsonResponse({'msg': '该账户已登出'})
    if is_login(request):
        return JsonResponse({'msg': ''})
    else:
        return JsonResponse({'msg': '该账户已过期，请重新登录'})


@csrf_exempt
def get_like_list(request):
    if not is_login(request):
        return JsonResponse({'msg': '非法访问'})
    username = request.POST['username']
    user = UserInfo.objects.get(username=username)
    t_1 = Favorites.objects.filter(user_id=user.id)
    t_like_list = t_1.filter(is_like=True)
    t_hate_list = t_1.filter(is_like=False)
    t_like_list = [model_to_dict(i)['movie'] for i in t_like_list]
    t_hate_list = [model_to_dict(i)['movie'] for i in t_hate_list]

    # t_like_list = [model_to_dict(i) for i in Movie.objects.filter(id__in=t_like_list)]
    res_like_list = []
    for i in Movie.objects.filter(id__in=t_like_list):
        like_ = model_to_dict(i)
        like_.update({'is_like': True,
                      'button1': i.id + '_1',
                      'button2': i.id + '_2'})
        res_like_list.append(like_)
    # t_hate_list = [model_to_dict(i) for i in Movie.objects.filter(id__in=t_hate_list)]
    res_hate_list = []
    for i in Movie.objects.filter(id__in=t_hate_list):
        hate_ = model_to_dict(i)
        hate_.update({'is_like': False,
                      'button1': i.id + '_1',
                      'button2': i.id + '_2'})
        res_hate_list.append(hate_)
    return JsonResponse({'msg': '',
                         'like_list': res_like_list,
                         'hate_list': res_hate_list
                         })


@csrf_exempt
def add_favor(request):
    if not is_login(request):
        return JsonResponse({'msg': '非法访问'})
    username = request.POST['username']
    user = UserInfo.objects.get(username=username)
    movie_id = request.POST.get('movie_id')
    favor = Favorites.objects.filter(user_id=user.id, movie_id=movie_id)
    if len(favor) > 0:
        favor = favor[0]
        if favor.is_like == True:
            favor.is_like = None
        else:
            favor.is_like = True
        # favor.is_like = True
        favor.pub_date = timezone.now()
        favor.save()
    else:
        favor = Favorites.objects.create(user_id=user.id, pub_date=timezone.now(),
                                         movie_id=movie_id, is_like=True)
    like_status = favor.is_like if favor.is_like is not None else "None"

    return JsonResponse({'msg': '',
                         'movie_id': movie_id,
                         'is_like': like_status
                         })


@csrf_exempt
def add_hate(request):
    if not is_login(request):
        return JsonResponse({'msg': '非法访问'})
    username = request.POST['username']
    user = UserInfo.objects.get(username=username)
    movie_id = request.POST.get('movie_id')
    favor = Favorites.objects.filter(user_id=user.id, movie_id=movie_id)
    if len(favor) > 0:
        favor = favor[0]
        if favor.is_like == False:
            favor.is_like = None
        else:
            favor.is_like = False
        favor.pub_date = timezone.now()
        favor.save()
    else:
        favor = Favorites.objects.create(user_id=user.id, pub_date=timezone.now(),
                                         movie_id=movie_id, is_like=False)
    like_status = favor.is_like if favor.is_like is not None else 'None'
    return JsonResponse({'msg': '',
                         'movie_id': movie_id,
                         'is_like': like_status
                         })


@csrf_exempt
def get_movie(request):
    if not is_login(request):
        return JsonResponse({'msg': '非法访问'})
    movie_id = request.POST.get('movie_id')
    con_user_id = request.user.id
    a_movie = Movie.objects.filter(id=movie_id)
    if len(a_movie) <= 0:
        return JsonResponse({'msg': '该电影不存在'})
    a_movie = a_movie[0]
    a_movie_like = Favorites.objects.filter(Q(movie_id=movie_id) & Q(user_id=con_user_id))
    is_like = None
    if len(a_movie_like) > 0:
        is_like = a_movie_like[0].is_like
    others = []
    favorelse = Favorites.objects.filter(movie_id=movie_id, is_like=True)
    favorelse_dict = [model_to_dict(i1) for i1 in favorelse]
    favorelse_dict_id = [i2['user'] for i2 in favorelse_dict]
    print(favorelse_dict_id)
    favorelse_movies = Favorites.objects.none()
    condition = Q(is_like=True)
    for iii in favorelse_dict_id:
        condition &= Q(user_id=iii, is_like=True)
        if iii == con_user_id:
            continue
        temp = Favorites.objects.filter(user_id=iii, is_like=True).order_by('?')
        favorelse_movies = favorelse_movies | temp
    favorelse_movies_dict = [model_to_dict(ii) for ii in favorelse_movies][:4]
    print(favorelse_movies_dict)
    for i_ in favorelse_movies_dict:
        favorelse_movies_dict_id = i_['movie']
        print(favorelse_movies_dict_id)
        others.append(model_to_dict(Movie.objects.filter(id=favorelse_movies_dict_id)[0]))

    return JsonResponse({'msg': '',
                         'data': model_to_dict(a_movie),
                         'is_like': is_like,
                         'button1': movie_id + '_1',
                         'button2': movie_id + '_2',
                         'others': others})


@csrf_exempt
def get_movie_list(request):
    if not is_login(request):
        return JsonResponse({'msg': '非法访问'})
    username = request.POST.get('username')
    if len(UserInfo.objects.filter(username=username)) == 0:
        return JsonResponse({'msg': '非法访问'})
    if not is_login(request):
        return JsonResponse({'msg': '非法访问'})
    # for_you = Movie.objects.filter(score__gte=9.5)[:8]
    # for_you = [model_to_dict(ii) for ii in for_you]
    for_you = recommend_service.get_rcm_list(request, RecommendList.objects.filter, op_code=1)
    ad_rcm = recommend_service.get_rcm_list(request, AdRecommendList.objects.filter, op_code=2)
    tags_rcm = recommend_service.get_rcm_list(request, TagRecommendList.objects.filter, op_code=3)
    info_rcm = recommend_service.get_rcm_list(request, SummaryRecommendList.objects.filter, op_code=4)
    # print(for_you)
    all_recommend = []
    i = 1
    all_recommend.append({
        'c_id': 1,
        'categoryName': '为你推荐',
        'movies': for_you})

    all_recommend.append({
        'c_id': 2,
        'categoryName': '标签',
        'movies': tags_rcm
    })

    all_recommend.append({
        'c_id': 3,
        'categoryName': '简介',
        'movies': info_rcm
    })

    all_recommend.append({
        'c_id': 4,
        'categoryName': '演员',
        'movies': ad_rcm
    })
    return JsonResponse({'recommends': all_recommend})


@csrf_exempt
def get_search_result(request):
    if not is_login(request):
        return JsonResponse({'msg': '非法访问'})
    search_str = request.POST.get('search_str')
    res = Movie.objects.filter(title__icontains=search_str) \
        .order_by('-score').order_by('-vote_count')
    res = res | Movie.objects.filter(tags__icontains=search_str) \
        .order_by('-score').order_by('-vote_count')
    res = res | Movie.objects.filter(actors__icontains=search_str) \
        .order_by('-score').order_by('-vote_count')
    res = res | Movie.objects.filter(info_summary__icontains=search_str) \
        .order_by('-score').order_by('-vote_count')
    res = res.distinct()[:20]
    res = [model_to_dict(ii) for ii in res]
    return JsonResponse({'msg': '',
                         'data': res})


@csrf_exempt
def get_cover(request):
    if not is_login(request):
        return JsonResponse({'msg': '非法访问'})
    res = BigCover.objects.order_by('?')[:1]
    res = [model_to_dict(ii) for ii in res]
    return JsonResponse({'msg': '',
                         'data': res})


@csrf_exempt
def age_recommend(request):
    if not is_login(request):
        return JsonResponse({'msg': '非法访问'})
    user = UserInfo.objects.filter(username=request.POST['username'])[0]
    userid = model_to_dict(user)
    user_id = userid['id']
    # print(user_id)
    record = Favorites.objects.filter(user_id=user_id, is_like=True)
    record_dict = [model_to_dict(ii) for ii in record]
    record_movies = Movie.objects.none()
    for i in record_dict:
        record_dict_id = i['movie']
        temp = Movie.objects.filter(id=record_dict_id)
        record_movies = record_movies | temp
    record_movies_dict = [model_to_dict(ii) for ii in record_movies]
    # print(record_movies_dict)
    record_movies_dict_date = []
    for iii in record_movies_dict:
        temp2 = iii['release_date']
        record_movies_dict_date.append(temp2[:4])
    record_movies_dict_date = list(map(int, record_movies_dict_date))
    # print(record_movies_dict_date)
    if len(record_movies_dict_date) < 5:
        return JsonResponse({'msg': '不符合'})
    record_mean = np.mean(record_movies_dict_date)
    record_var = np.var(record_movies_dict_date)
    record_std = np.std(record_movies_dict_date)
    # print(record_std)
    # print(record_var)
    record_re = Movie.objects.none()
    record_mean = math.ceil(record_mean)
    if record_std > 30:
        return JsonResponse({'msg': '不符合'})

    record_re1 = Movie.objects.filter(release_date__icontains=str(record_mean - 2)).order_by('?')
    # print(record_re1)
    record_re2 = Movie.objects.filter(release_date__icontains=str(record_mean - 1)).order_by('?')
    record_re3 = Movie.objects.filter(release_date__icontains=str(record_mean)).order_by('?')
    record_re4 = Movie.objects.filter(release_date__icontains=str(record_mean + 1)).order_by('?')
    record_re5 = Movie.objects.filter(release_date__icontains=str(record_mean + 2)).order_by('?')
    record_re = record_re1 | record_re2 | record_re3 | record_re4 | record_re5
    last = record_re.count() - 1
    # x = np.random.randint(0, last, 6)
    x = np.random.choice(last, 6, replace=False)
    record_up =[]
    for i in x:
        record_up.append(model_to_dict(record_re[int(i)]))
    # print(record_up)
    return JsonResponse({'msg': '',
                         'data': record_up})
